package com.lovo.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.bean.UserInfoBean;
import com.lovo.result.GlobalHandleException;
import com.lovo.result.ResponseResult;
import com.lovo.result.ResultCode;
import com.lovo.result.UserValid;
import com.lovo.service.IUserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.Session;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bdk
 * @since 2021-03-10
 */
@RestController
@RequestMapping("users")
@ResponseResult
@Api("用户注册和登录以及查看用户信息的控制器")
public class UserInfoController {
    @Resource
    private IUserInfoService userInfoService;
    @PostMapping("login")
    public Object login(String code, String pwd, HttpServletRequest request) throws GlobalHandleException {
        UsernamePasswordToken token = new UsernamePasswordToken(code, DigestUtils.sha256Hex(pwd));
        Subject currentUser = SecurityUtils.getSubject();
        try{
            //主体提交登录请求到SecurityManager
            currentUser.login(token);
        }catch(IncorrectCredentialsException ice){
            throw new GlobalHandleException(ResultCode.USER_PASS_ERROR);
        }catch (UnknownAccountException uae){
            throw new GlobalHandleException(ResultCode.USER_NOT_EXIST);
        }catch (AuthenticationException ae){
            throw new GlobalHandleException(ResultCode.USER_AUTHENTICATION_ERROR);
        }catch (AuthorizationException ae){
            throw new GlobalHandleException(ResultCode.USER_AUTHORIZATION_ERROR);
        }
        return currentUser.getPrincipal();
    }

    @GetMapping("getUser")
    @ApiOperation(value = "获取登录对象")
    @UserValid
    public Object getUser(HttpServletRequest request){
        return SecurityUtils.getSubject().getPrincipal();
    }

    @GetMapping("checkFavor")
    public Object checkFavor(Integer discussId){
        UserInfoBean user = (UserInfoBean) SecurityUtils.getSubject().getPrincipal();
        if (userInfoService.checkFavor(user.getUserInfoId(), discussId)){
            return "ok";
        }
        return "no";
    }

}

